<?php

namespace app\common\model;

use think\Db;
use think\Model;
use think\Validate;

/**
 * 作业表模型
 */
class Homework extends Model
{
    // 表名,不含前缀
    protected $name = 'homework';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    /**
     * 关联学生表
     *
     * @return void
     */
    public function Students()
    {
        return $this->belongsTo('user', 'student_id');
    }

    /**
     * 列表
     */
    public function dataList($dis)
    {
        $res = $this->where([]);

        foreach ($dis as $field => $condition) {
            if(Validate::is($condition, 'array') && isset($condition[0]) && $condition[0] === 'in') {
                // 处理 IN 条件
                $res->whereIn($field, $condition[1]);
            } else {
                // 普通条件
                $res->where($field, $condition);
            }
        }
        
        return $res->select();
    }

    /**
     * 总数
     */
    public function dataCount($dis, $group = null)
    {
        $res = $this->where([]);

        foreach ($dis as $field => $condition) {
            if(Validate::is($condition, 'array') && isset($condition[0]) && $condition[0] === 'in') {
                // 处理 IN 条件
                $res->whereIn($field, $condition[1]);
            } else {
                // 普通条件
                $res->where($field, $condition);
            }
        }
        if($group){
            $res->group($group);
        }
        
        return $res->count();
    }

    public function dataMemberId($joinTable = null, $joinCondition = null ,$dis = [], $column = 'har.assignment_id')
    {
        $query = $this->where($dis);

        if ($joinTable && $joinCondition) {
            $query->alias('h')
                ->join($joinTable, $joinCondition);
        }

        $res = $query->column($column);

        return $res;
    }

    public function dataValue($joinTable = null, $joinCondition = null ,$dis = [],$backField = 'h.id')
    {
        $query = $this->where($dis);

        if ($joinTable && $joinCondition) {
            $query->alias('h')
                ->join($joinTable, $joinCondition);
        }

        $res = $query->value($backField);

        return $res;
    }
}
